package com.hlcity.service.impl;

import org.springframework.transaction.annotation.Transactional;

import com.hlcity.domain.Content;
import com.hlcity.domain.ContentOfCategory;
import com.hlcity.mapper.CategoryMapper;
import com.hlcity.mapper.ContentMapper;
import com.hlcity.mapper.ContentOfCategoryMapper;
import com.hlcity.service.ContentService;

@Transactional
public class ContentServiceImpl implements ContentService{
	private ContentMapper contentMapper;

	private ContentOfCategoryMapper contentOfCategoryMapper;
	
	private CategoryMapper categoryMapper;

	public void setContentMapper(ContentMapper contentMapper) {
		this.contentMapper = contentMapper;
	}

	public void setContentOfCategoryMapper(
			ContentOfCategoryMapper contentOfCategoryMapper) {
		this.contentOfCategoryMapper = contentOfCategoryMapper;
	}

	public void setCategoryMapper(CategoryMapper categoryMapper) {
		this.categoryMapper = categoryMapper;
	}

	public void add(Content content) {
		contentMapper.insertContent(content);
		Integer conId=content.getId();
		Integer[] catIds = content.getCatIds();
		insertCats(conId,catIds);
		
	}
	
	public Content getById(Integer id){
		Content content=contentMapper.getContentById(id);
		if(content!=null)
			content.setCats(categoryMapper.getCatsByContentId(id));
		return content;
	}
	
	public void delete(Integer id){
		contentMapper.deleteContent(id);
		contentOfCategoryMapper.deleteContentOfCategory(id);
	}
	
	public void update(Content content){
		contentMapper.updateContent(content);
		contentOfCategoryMapper.deleteContentOfCategory(content.getId());
		Integer[] catIds = content.getCatIds();
		insertCats(content.getId(),catIds);
	}
	
	private void insertCats(Integer conId,Integer[] catIds){
		if(catIds==null)
			return;
		for (Integer catId : catIds) {
			contentOfCategoryMapper.insertContentOfCategory(new ContentOfCategory(conId,catId));
		}
	}
}
